package com.scfire.user

import grails.converters.JSON
import grails.transaction.Transactional

import java.text.DecimalFormat
import java.text.SimpleDateFormat
import javax.servlet.http.HttpSession

import net.sf.json.JSONArray
import net.sf.json.JSONObject

import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.paic.qhcs.util.*
import com.paic.qhcs.util.entry.ResultEntry
import com.scfire.baseInfo.Gson
import com.scfire.cert.CreditRank
import com.scfire.fund.FDonate
import com.scfire.message.*
import com.scfire.project.Donate
import com.scfire.project.Project
import com.scfire.project.ProjectClosing
import com.scfire.project.ProjectFeedback
import com.scfire.security.Member
import com.scfire.userinfo.*
import com.scfire.util.SCFIREConstants
import com.scfire.weixin.WeiXinConstants
class UserController {
	
	def Log LOG = LogFactory.getLog(UserController.class)
	
	def springSecurityService
	def deviceInfoService
	def weiXinService
	def CCPSMSService
	
	def mongo
	def grailsApplication
	/**
	 * 个人中心
	 * @param null
	 * @return null
	 *
	 * **/
	
	def userDonate(){
		String unionid = params.unionid;
		if(unionid==null){
			notFound()
			return
		}else{
		  def member = Member.findByOtherUnionid(unionid)
		  if(member==null){
			  notFound()
			  return
		  }
		HttpSession session = request.getSession(true)
		session.setAttribute("otherUnionId", unionid)
		session.setAttribute("LOGIN_REDIRECT_URL", "/user/userMyDonateDetail")
		String oauthCallBack = WeiXinConstants.oauth_url+"?appid="+WeiXinConstants.appid+"&redirect_uri="+URLEncoder.encode(WeiXinConstants.login_url+"?type=微信mobile端")+"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"
			redirect(url:oauthCallBack)
			return
		}
	}
	
	
	
	def userCenter(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		
		//微信分享参数
		def url = WeiXinConstants.server + "/user/userCenter"
		if(request.getQueryString()){
			url = (url + "?" + request.getQueryString())
		}
		Map map = weiXinService.jsapiTicketSign(url)
		def noncestr = map.get("noncestr")
		def jsapi_ticket = map.get("jsapi_ticket")
		def timestamp = map.get("timestamp")
		def sign = map.get("sign")
		def imgUrl =  WeiXinConstants.server+"/images/scfire.png"
		def shareUrl = WeiXinConstants.server
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "usercentermb", model: [user:user,roles:roles]
				}
				if("mobile".equals(str)){
					render view: "usercentermb", model: [user:user,roles:roles  , appid : WeiXinConstants.appid , timestamp : timestamp , nonceStr : noncestr , signature : sign,shareUrl:shareUrl , imgUrl : imgUrl]
				}
			}
			json {
				
			}
		}
	}
	
	
	/**
	 * 用户捐赠列表
	 * @return
	 */
	def userDonates(){
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		Set<Donate> donates = null //部分
		try{
			Member member = (Member)user
			def Criteriadonate = Donate.createCriteria()
			def dfc = {
				eq("member",member.id)
				order("date", "desc")
			}
			params.max=20
			donates = Criteriadonate.list(params,dfc)
		}
		catch(Exception e){
			LOG.error("userDonates get exception."+e.getMessage())
		}
		withFormat {
			html {
					render view: "usercenterdonates", model: [user:user, donates:donates]
			}
			json {
					render donates as JSON
			}
		}
	}
	
	/**
	 * 用户项目列表
	 * @return
	 */
	def userProjects(){
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		Set<Project> projects = null
		try{
			Member member = (Member)user
			def Criteriaproject = Project.createCriteria()
			def pfc = {
				eq("member",member.id)
			}
			params.max=20
			projects = Criteriaproject.list(params,pfc)
		}
		catch(Exception e){
			LOG.error("userProjects get exception."+e.getMessage())
		}
		withFormat {
			html {
					render view: "usercenterprojects", model: [user:user, projects:projects]
			}
			json {
					render projects as JSON
			}
		}
		
	}
	
	/**
	 * 用户相关动态列表
	 * @return
	 */
	def projectFeedBacks(){
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		Set<ProjectFeedback> projectFeedBacks = new TreeSet<ProjectFeedback>();
		try{
			Member member = (Member)user
			def Criteria = ProjectFeedback.createCriteria()
			def pfc = {
				eq("project",member.project)
			}
			params.max=20
			def myfeedbacks = Criteria.list(params,pfc)//项目动态
			
			for(ProjectFeedback feedback :myfeedbacks){
				projectFeedBacks.add(feedback);
			}
			def donates = Donate.findAllByMember(member.id)
			for(Donate donate:donates){
				def feedbacks = ProjectFeedback.findAllByProject(donate.project, [sort: "date", order: "desc"])
				if (feedbacks!= null){
					for (def feedback: feedbacks){
						projectFeedBacks.add(feedback)
					}
				}
			}
		}
		catch(Exception e){
			LOG.error("userProjects get exception."+e.getMessage())
		}
		withFormat {
			html {
					render view: "usercenterfeedbacks", model: [user:user, projectFeedBacks:projectFeedBacks]
			}
			json {
					render projectFeedBacks as JSON
			}
		}
	}
	
	
	
	/**
	 * 我的捐赠详情
	 * @param null
	 * @return null
	 *
	 * **/
	def userMyDonateDetail(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		float donatesTotal =0.0
		def donateAll=0
		def fdonatesTotal =0.0
		def projectsTotal = 0
		params.max=5
		int offsets = params.offset ? params.offset.toInteger() : 0
		Set<Integer> projects = null
		Member member = (Member)user
		try{
			def Criteriadonate = Donate.createCriteria()
			def Criteriaproject = Project.createCriteria()
			def df= {
			    eq("member",member.id)
				order("date", "desc")
			}
			
			def dfc = {
					eq("member",member.id)
					projections {
						distinct ("project")		
						   }
				order("createDate", "desc")
			}
			
		    projects = Criteriadonate.listDistinct(dfc)
				println projects.size()
				
				
			def donates = Donate.findAllByMember(member.id)
			
			projectsTotal=projects.size()
			donateAll = donates.size()
			for(Donate d:donates){
				donatesTotal+=d.money
				def fDonate=FDonate.findByDonate(d.id)
				if(fDonate){
					fdonatesTotal+=fDonate?.donate_fee
				}
				
			}
			

		}catch(Exception e){
			LOG.error("userCenterDetail get exception."+e.getMessage())
			e.printStackTrace()
		}
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "mydonatemb", model: [user:user,projects:projects,projectsTotal:projectsTotal,donatesTotal:donatesTotal,fdonatesTotal:fdonatesTotal,donateAll:donateAll]
				}
				if("mobile".equals(str)){
					render view: "mydonatemb", model: [user:user,projects:projects,projectsTotal:projectsTotal,donatesTotal:donatesTotal,fdonatesTotal:fdonatesTotal,donateAll:donateAll]
				}
			}
			
		}
	}
	
	
	def userMyDonateDetailJSON(){
		
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		params.max=5
		int offsets = params.offset ? params.offset.toInteger() : 0
		Set<Integer> projects = null
		Member member = (Member)user
		try{
			def Criteriadonate = Donate.createCriteria()
			def df= {
				eq("member",member.id)
				order("date", "desc")
			}
			
			def dfc = {
					eq("member",member.id)
					projections {
						distinct ("project")
						   }
				order("createDate", "desc")
			}
			
			projects = Criteriadonate.listDistinct(dfc)
				
		}catch(Exception e){
			LOG.error("userCenterDetail get exception."+e.getMessage())
			e.printStackTrace()
		}
		
		withFormat {
			json {
				JSONArray fRulesjson = new JSONArray()
				java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");
				int offset = 0
				for(int project:projects){
					if(offset < offsets){
						offset++
						
						continue;
					 }else if(offset>=(offsets+params.max.toInteger())){
					 offset++
					   break
					 }else{
					 offset++
						int totalDonateSize=0
						def projectDonate=0
						def projectFDonate=0
						//def donates= project.donates
						def donatess = Donate.findAllByProjectAndMember(project,member.id)
						for(Donate d:donatess){
								totalDonateSize++
								projectDonate+=d.donate_fee
								def fDonate=FDonate.findByDonate(d.id)
								if(fDonate){
									projectFDonate+=fDonate?.donate_fee
								}
						}
						JSONObject json = new JSONObject()
						def project2 = Project.findById(project)
						json.put("projectid", project2.id)
						json.put("donatessize", totalDonateSize)
						json.put("img", project2.img)
						json.put("name", project2.name)
						json.put("progress", project2.progress)
						json.put("verified", project2.verified)
						json.put("savemoney", project2.realAmount)
						json.put("description", project2.description)
						if(projectDonate==0){
							json.put("projectDonate", 0)
						}else{
						json.put("projectDonate", projectDonate)
						}
						if(projectFDonate==0){
							json.put("projectFDonate", 0)
						}else{
						json.put("projectFDonate", (projectFDonate/100))
						}
						fRulesjson.add(json)
					}
					
				}
				
				render fRulesjson as JSON
				
			}
		}
	}
	
	/**
	 * 我的捐赠项目详情
	 * @param null
	 * @return null
	 *
	 * **/
	def userMyDonateDetailByProject(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		def donatesTotal =0
		def donateAll=0
		def fdonatesTotal =0.0
		def projectsTotal = 0.0
		Set<Project> projects = null
			Member member = (Member)user

			Project project
			Set<Donate> donates = null
			try {
				project = Project.findById(Long.valueOf(params.projectid))
				
				/*def donatesAll=Donate.findAllByMember(member.id)
				for(Donate donate:donatesAll){
					//更改捐赠码为数字
					if(!donate?.donateNoNew){
						long timestap = System.currentTimeMillis()/1000
						donate.donateNoNew = donate.project.id+""+member.id+""+timestap
						donate.save(flush : true)
					}
				}*/
				donates =Donate.findAllByProjectAndMember(project.id,member.id,[ sort:"date", order:"desc"])
		}catch(Exception e){
			LOG.error("userCenterDetail get exception."+e.getMessage())
			e.printStackTrace()
		}
		
		withFormat {
			json {
				JSONArray fRulesjson = new JSONArray()
				java.text.DecimalFormat   df   =new   java.text.DecimalFormat("#.00");
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
				for(Donate donate:donates){
					JSONObject json = new JSONObject()
					json.put("donateNoNew", donate.donateNoNew)
					if(donate?.donate_fee){
						json.put("money", donate.donate_fee)
					}else{
					
					json.put("money", 0)
					}
					def fDonate = FDonate.findByDonate(donate.id)
					if(fDonate){
						json.put("donate_fee", fDonate?.donate_fee/100)
				   }else{
				   json.put("donate_fee", 0)
				   }
				   json.put("date", sdf.format(donate.date).substring(5))
					fRulesjson.add(json)
				}
				render fRulesjson as JSON
				
			}
		}
	}
	
	
	/**
	 * 我的项目
	 * @param null
	 * @return null
	 *
	 * **/
		/**
	 * 我的项目
	 * @param null
	 * @return null
	 *
	 * **/
	def userMyProjectDetail(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		Set<Donate> donates = null
		Set<Project> projectsAll = null
		Set<Donate> donatesAll = null //全部
		def donatesTotalcount =0
		def projectsTotal = 0
		int totaldonateMoney=0
		int totalfdonateMoney=0
		int donatesAllcount=0
		
		Set<Project> projectDonate = new HashSet<Project>();
		
			Member member = (Member)user
			

			def Criteriadonate = Donate.createCriteria()
			
			params.max=20
			projectsAll = Project.findAllByMember(member.id)
			projectsTotal=projectsAll.size()
			
			for(Project p:projectsAll){
				donatesTotalcount+=p?.donateNum
				totaldonateMoney+=(p.realAmount)
			}
			donatesAll = Donate.findAllByMember(member.id)
			donatesAllcount=donatesAll.size()
			//捐款项目动态
			if(donatesAll!=null){
				for(Donate donate:donatesAll){
					//更改捐赠码为数字
					if(!donate?.donateNoNew){
						long timestap = System.currentTimeMillis()/1000
						donate.donateNoNew = donate.project+""+member.id+""+timestap
						donate.save(flush : true)
					}
				}
			}
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "myProjectDetailmb", model: [user:user,projectsTotal:projectsTotal,donatesTotalcount:donatesTotalcount,totaldonateMoney:totaldonateMoney]
				}
				if("mobile".equals(str)){
					render view: "myProjectDetailmb", model: [user:user,projectsTotal:projectsTotal,donatesTotalcount:donatesTotalcount,totaldonateMoney:totaldonateMoney]
				}
			}
			json {
				params.max=20
				def Criteriaproject = Project.createCriteria()
				def dfc = {
					eq("member",member.id)
					order("updateDate", "desc")
				}
				def projectss = Criteriaproject.list(params,dfc)
				JSONArray projects = new JSONArray()
				for (Project project :projectss){
					
					JSONObject json = new JSONObject()			
					json.put("id",project.id)
					json.put("img",project.img)
					json.put("name",project.name)
					json.put("progress",project.progress)
					json.put("rest",project.rest)
					json.put("apliNum",project.apliNum)
					json.put("verified",project.verified)
					if(project.verified=="doing"){
						ProjectClosing projectClosingInstance = ProjectClosing.findByProject(project.id)
						if(projectClosingInstance!=null){
							json.put("closingverified",projectClosingInstance.verified)
						}else{
							json.put("closingverified","none")
						}
					}else{
						json.put("closingverified","none")
					}
					
					if(project?.donateNum){
						json.put("donatenum",project?.donateNum)
					}else{
					json.put("donatenum",0)
					}
					DecimalFormat decimalFormat=new DecimalFormat("#0.00")
					String donatemoney = decimalFormat.format(project.realAmount)
					json.put("donatemoney",donatemoney)
					Date date;
					if(project?.endDate){
						date= project?.endDate
					}else{
					date= new Date();
					}
					long dates= (date.getTime()-new Date().getTime())/(24*60*60*1000)
					if(dates<0){
						json.put("endDate",0)
					}else{
					json.put("endDate",dates)
					}
					
					
					json.put("description",project.description)
					projects.add(json)
				}
				render projects as JSON
				
			}
		}
	}
	
	
	
	/**
	 * 反馈详情
	 * @param null
	 * @return null
	 *
	 * **/
	def userFeedBackDetail(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		//获取信息详情
		String detail = params.detail
		int offsets = params.offset ? params.offset.toInteger() : 0
		Set<Project> projects = null
		Set<Project> projectsAll = null
		Set<Donate> donates = null //部分
		Set<Donate> donatesAll = null //全部
		def donatesTotal =0
		def donatesTotalMoney=0
		def fdonatesTotalMoney=0
		def projectsTotal = 0
		def projectfeedbackTotal = 0
		Set<Project> projectDonate = new HashSet<Project>();
		//总捐赠明细<key: 项目号，value：总捐赠额>
		Map<String,Double> donatesDetail = new HashMap<String,Double>();
		List<ProjectFeedback> projectFeedBacks= new ArrayList<ProjectFeedback>();
		Set<ProjectFeedback> subprojectFeedBacks = new TreeSet<ProjectFeedback>()

		//donate json列表
		JSONArray donatesjson = new JSONArray();
		//feedback
		
			Member member = (Member)user
			def Criteriadonate = Donate.createCriteria()
			def Criteriaproject = Project.createCriteria()
			params.max=20
			projectsAll = Project.findAllByMember(member.id)
			donatesAll =  Donate.findAllByMemer(member.id)
			for(Donate d:donatesAll){
				def project2 = Project.findById(d.project)
				projectsAll.add(project2)
			}
			Set<Integer> projectids = new HashSet<Project>();
			for(def project: projectsAll){
				projectids.add(project.id);
			}
			
			//自己项目动态
			for(int id : projectids){
				def feedbacks = ProjectFeedback.findAllByProject(id, [sort: "date", order: "desc"])
				println "--------------------"+id+"--------------------"
				if (feedbacks){
					for (def feedback: feedbacks){
						projectFeedBacks.add(feedback)
					}
				}
			}
			
			//捐款项目动态
			if(donatesAll!=null){
				for(Donate donate:donatesAll){
					
					//更改捐赠码为数字
					if(!donate?.donateNoNew){
						long timestap = System.currentTimeMillis()/1000
						donate.donateNoNew = donate.project+""+member.id+""+timestap
						donate.save(flush : true)
					}
				}
			}
			projectfeedbackTotal = projectFeedBacks?.size()
				
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "myFeedbackmb", model: [user:user,donates:donatesAll,detail:detail,donatesTotal:donatesTotal,projectsTotal:projectsTotal,projectfeedbackTotal:projectfeedbackTotal,donatesTotalMoney:donatesTotalMoney,fdonatesTotalMoney:fdonatesTotalMoney]
				}
				if("mobile".equals(str)){
					render view: "myFeedbackmb", model: [user:user,projects:projects,donates:donates,detail:detail, donatesTotal:donatesTotal,projectsTotal:projectsTotal,projectfeedbackTotal:projectfeedbackTotal,donatesTotalMoney:donatesTotalMoney,fdonatesTotalMoney:fdonatesTotalMoney]
				}
			}
			json {
				JSONArray feedbackjson = new JSONArray();
				println offsets
				int offset = 0
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm")
					for( ProjectFeedback feedback:projectFeedBacks){
					if(offset < offsets){
						offset++
						continue;
					 }else if(offset>=(offsets+params.max.toInteger())){
					 offset++
					   break
					 }else{
					 offset++
					
					  JSONObject fjson = new JSONObject();
					  def project = Project.findById(feedback.project)
					  fjson.put("id", feedback?.id)
					  fjson.put("projectid", project.id)
					  fjson.put("projectname", project.name)
					  fjson.put("date",sdf.format(feedback.date).substring(5))
					  fjson.put("text", feedback.text)
					  fjson.put("memberid", feedback.member)
					  fjson.put("img1", feedback.img1)
					  fjson.put("img2", feedback.img2)
					  fjson.put("img3", feedback.img3)
					  fjson.put("img4", feedback.img4)
					  fjson.put("img5", feedback.img5)
					  fjson.put("img6", feedback.img6)
					  fjson.put("img7", feedback.img7)
					  fjson.put("img8", feedback.img8)
					  feedbackjson.add(fjson)
					  
					}
				}
				println feedbackjson
				render feedbackjson as JSON
			}
		}
	}
	
	
	/**
	 * 个人中心详情
	 * @param null
	 * @return null
	 *
	 * **/
	def userCenterDetail(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		//获取信息详情
		String detail = params.detail
		int offsets = params.offset ? params.offset.toInteger() : 0

		Set<Project> projects = null
		Set<Project> projectsAll = null
		Set<Donate> donates = null //部分
		Set<Donate> donatesAll = null //全部
		def donatesTotal =0
		def projectsTotal = 0
		def projectfeedbackTotal = 0
		Set<Project> projectDonate = new HashSet<Project>();
		//总捐赠明细<key: 项目号，value：总捐赠额>
		Map<String,Double> donatesDetail = new HashMap<String,Double>();
		Set<ProjectFeedback> projectFeedBacks= new TreeSet<ProjectFeedback>();
		Set<ProjectFeedback> subprojectFeedBacks = new TreeSet<ProjectFeedback>()

		//donate json列表
		JSONArray donatesjson = new JSONArray();
		//feedback
		JSONArray feedbackjson = new JSONArray();
		try{
			Member member = (Member)user

			def Criteriadonate = Donate.createCriteria()
			def Criteriaproject = Project.createCriteria()
			def dfc = {
				eq("member",member.id)
				order("date", "desc")
			}
			def pfc = {
				eq("member",member.id)
			}
			params.max=20
			projectsAll = Project.findAllByMember(member.id)
			donatesAll = Donate.findAllByMember(member.id)
			donatesTotal = donatesAll.size()
			projectsTotal = projectsAll.size()

			//自己项目动态
			for(def project: projectsAll){
				def feedbacks = ProjectFeedback.findAllByProject(project.id, [sort: "date", order: "desc"])
				if (feedbacks!= null){
					for (def feedback: feedbacks){
						projectFeedBacks.add(feedback)
					}
				}
			}

			//捐款项目动态
			for(Donate donate:donatesAll){

				//更改捐赠码为数字
				if(!donate?.donateNoNew){
					long timestap = System.currentTimeMillis()/1000
					def project2 = Project.findById(donate.project)
					donate.donateNoNew = project2.id+""+member.id+""+timestap
					donate.save(flush : true)
				}

				def feedbacks = ProjectFeedback.findAllByProject(donate.project, [sort: "date", order: "desc"])
				if (feedbacks!= null){
					for (def feedback: feedbacks){
						projectFeedBacks.add(feedback)
					}
				}

				//捐过的项目
				def pDonate =Project.findById(donate.project) 
				if (pDonate!= null){
					projectDonate.add(pDonate)
				}

			}
			
			projectfeedbackTotal = projectFeedBacks?.size()
			
			Iterator<ProjectFeedback> it = projectFeedBacks.iterator();
			int offset = 0
	
			while (it.hasNext()) {
				if(offset < offsets){
				   it.next();
				   offset++;
				}else if(offset>=(offsets+params.max.toInteger())){
				  break
				}else{
				  def feedback = it.next()
				  subprojectFeedBacks.add(feedback)
				  JSONObject fjson = new JSONObject();
				  def project2 = Project.findById(feedback.project)
				  fjson.put("id", feedback.id)
				  fjson.put("projectid", project2.id)
				  fjson.put("projectname", project2.name)
				  fjson.put("date",feedback.date.getMonth()+"-"+feedback.date.getDay()+" "+feedback.date.getHours()+":"+feedback.date.getMinutes())
				  fjson.put("text", feedback.text)
				  fjson.put("memberid", feedback.member.id)
				  fjson.put("img1", feedback.img1)
				  fjson.put("img2", feedback.img2)
				  fjson.put("img3", feedback.img3)
				  fjson.put("img4", feedback.img4)
				  fjson.put("img5", feedback.img5)
				  fjson.put("img6", feedback.img6)
				  fjson.put("img7", feedback.img7)
				  fjson.put("img8", feedback.img8)
				  
				  feedbackjson.add(fjson)
				  offset++;
				} 
			 
			}
			
			//分页显示 捐赠
			donates = Criteriadonate.list(params,dfc)
			for(Donate donate:donates){//分页显示
				JSONObject djson = new JSONObject();
				def project2 = Project.findById(donate.project)
				djson.put("projectid",project2.id)
				djson.put("donatesize", project2.donateNum)
				djson.put("projectimg",project2.img)
				djson.put("projectname", project2.name)
				djson.put("projectprogress",project2.progress)
				djson.put("projectverified",project2.verified)
				djson.put("projectrest",project2.rest)
				if(donate.donate_fee!=null)
					djson.put("donate_fee",donate.donate_fee)
				if(donate.money!=null)
					djson.put("money",donate.money)
				djson.put("date",donate.date.getYear()+"-"+donate.date.getMonth()+"-"+donate.date.getDay())
				djson.put("donateNoNew",donate.donateNoNew)
				donatesjson.add(djson)
			}
			
			//分页显示发起
			projects = Criteriaproject.list(params,pfc)
			

		}catch(Exception e){
			LOG.error("userCenterDetail get exception."+e.getMessage())
		}
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "usercenterdetail", model: [user:user,projects:projectsAll,donates:donatesAll,detail:detail,projectFeedBacks:projectFeedBacks,donatesTotal:donatesTotal,projectsTotal:projectsTotal,projectfeedbackTotal:projectfeedbackTotal]
				}
				if("mobile".equals(str)){
					render view: "usercenterdetailmb", model: [user:user,projects:projects,donates:donates,detail:detail, projectFeedBacks:subprojectFeedBacks,donatesTotal:donatesTotal,projectsTotal:projectsTotal,projectfeedbackTotal:projectfeedbackTotal]
				}
			}
			json {
				if(detail.equals("mydonate")){	
					render donatesjson as JSON
				}else if(detail.equals("mynews")){
					render feedbackjson as JSON
				}else if(detail.equals("myproject")){
				    render projects as JSON
				}
			}
		}
	}
	

	
	/**
	 * 查看别人个人中心详情
	 * @param null
	 * @return null
	 *
	 * **/
	def userCenterDetailOther(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		//def user = springSecurityService.getCurrentUser()
		def user = null
		def roles = springSecurityService.getAuthentication()?.authorities
		//获取信息详情
		String detail = params.detail
		
		Member member = null
		Set<Project> projects = null
		Set<Donate> donates = null
				
		Set<ProjectFeedback> projectFeedBacks= new HashSet<ProjectFeedback>();
		
		try{			
			member = Member.findById(Long.valueOf(params.memberid))
			if(member==null){
				notFound()
				return
			}
			user = member
			projects = Project.findAllByMember(member.id)
			
			
		}catch(Exception e){
			LOG.error("userCenterDetailOther get exception."+e.getMessage())
		}
		
		withFormat {
			html {
				if("pc".equals(str)){
					//render view: "usercenterdetailothermb", model: [user:user,projects:projects,donates:donates,detail:detail,projectFeedBacks:projectFeedBacks]
					render view: "usercenterdetailothermb", model: [user:user,projects:projects,str:str]
				}
				if("mobile".equals(str)){
					//render view: "usercenterdetailothermb", model: [user:user,projects:projects,donates:donates,detail:detail, projectFeedBacks:projectFeedBacks]
					render view: "usercenterdetailothermb", model: [user:user,projects:projects,str:str]
				}
			}
			json {
				
			}
		}
	}

	
	/**
	 * 删除自己的反馈进展
	 * 个人中心动态
	 */
	def deleteProjectFeedBack(){
		def map = [:]
		Member user = springSecurityService.getCurrentUser()
		def id = params.id
		if(!id){
			map.put("info","参数缺失")
			map.put("result",false)
			render map as JSON
			return
		}
		
		def feedBack = ProjectFeedback.findByIdAndMember(id , user.id)
		if(!feedBack){
			map.put("info","未找到属于您的反馈进展信息")
			map.put("result",false)
			render map as JSON
			return
		}
		feedBack.delete(flush : true)
		map.put("info","删除成功")
		map.put("result",true)
		render map as JSON
		return
		
	}
	
	/**
	 * 个人信息认证
	 * @param null
	 * @return null
	 *
	 * **/
	def userAuth(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		def member = (Member)user
		
		withFormat {
			html {
				if(member.verify != null){
					redirect (action:"userAuthEdit")
				}
				else{
					if("pc".equals(str)){
						render view: "userauth", model: [user:user,roles:roles]
					}
					if("mobile".equals(str)){
						render view: "userauthmb", model: [user:user,roles:roles]
					}
				}
			}
			json {
				
			}
		}
	}
	
	/**
	 * 个人信息修改
	 * @param null
	 * @return null
	 *
	 * **/
	def userAuthEdit(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		Member member = (Member)user
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "userauthEdit", model: [member:member,roles:roles, user:member]//PC layout里面的个人信息
				}
				if("mobile".equals(str)){
					render view: "userauthmbEdit", model: [member:member,roles:roles]
				}
			}
			json {
				
			}
		}
	}
	
	/**
	 * 查看个人信息
	 * @param null
	 * @return null
	 *
	 * **/
	def userAuthInfo(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "userauthinfomb", model: [user:user,roles:roles]
				}
				if("mobile".equals(str)){
					render view: "userauthinfomb", model: [user:user,roles:roles]
				}
			}
			json {
				
			}
		}
	}
	/**
	 * 绑定个人手机号
	 * @param null
	 * @return null
	 *
	 ***/
	def modifyMoblie(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()

		Member member =  Member.findById(user.id)
		render view:"mobileModifymb" , model:[user:member]
	}
	
	/**
	 * 修改个人信息 、支持单项修改
	 * @param null
	 * @return null
	 *
	 ***/
	def userInfoModify(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()

		Member member = (Member)user
				
		try{		
			if(params.bankCard){
				member.bankCard = params.bankCard
			}
			if(params.bankName){
				member.bankName = params.bankName
			}
			if(params.subBranch){
				member.subBranch = params.subBranch
			}
			if(params.gender){
				member.sex = params.gender
			}
			if(params.description){
				member.description = params.description
			}
			if(params.realName){
				member.realName = params.realName
			}
			if(params.nickName){
				member.nickname = params.nickName
			}
			if(params.mobile){
				member.mobile = params.mobile
			}
			if(params.headimgurl){
				member.headimgurl = params.headimgurl
			}
			if(params.school){
				member.school = params.school
			}
			def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
			DBCollection projectCollection = db.getCollection("member")
			DBObject queryCondition= new BasicDBObject()
			queryCondition.put("_id",member.id)
			
			
			if(params.detail){//填写了地址详情的信息
				if(member.addressinfo == null){
					Address addr = new Address();
					addr.province = params.province
					addr.city = params.city
					addr.area = params.area
					addr.detail = params.detail
					addr.phone = params.phone
					addr.name = params.name
					addr.member = member
					addr.save(flush:true)
					
					BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("bankCard", member?.bankCard)
						.append("bankName", member?.bankName)
						.append("subBranch", member?.subBranch)
						.append("sex", member?.sex)
						.append("description", member?.description)
						.append("nickname", member?.nickname)
						.append("realName", member?.realName)
						.append("mobile", member?.mobile)
						.append("headimgurl", member?.headimgurl)
						.append("school",member?.school)
						.append("addressinfo",addr.id)
						
						)
					projectCollection.update(queryCondition, updateParameter,true,true)
					
				}
				else{
					Address addr = member.addressinfo
					addr.province = params.province
					addr.city = params.city
					addr.area = params.area
					addr.detail = params.detail
					addr.phone = params.phone
					addr.name = params.name
					addr.member = member
					addr.save(flush:true)
					
					BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("bankCard", member?.bankCard)
						.append("bankName", member?.bankName)
						.append("subBranch", member?.subBranch)
						.append("sex", member?.sex)
						.append("description", member?.description)
						.append("nickname", member?.nickname)
						.append("realName", member?.realName)
						.append("mobile", member?.mobile)
						.append("headimgurl", member?.headimgurl)
						.append("school",member?.school)
						.append("addressinfo",addr.id)
						
						)
					projectCollection.update(queryCondition, updateParameter,true,true)
				}
			}else{
			BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("bankCard", member?.bankCard)
				.append("bankName", member?.bankName)
				.append("subBranch", member?.subBranch)
				.append("sex", member?.sex)
				.append("description", member?.description)
				.append("nickname", member?.nickname)
				.append("realName", member?.realName)
				.append("mobile", member?.mobile)
				.append("headimgurl", member?.headimgurl)
				.append("school",member?.school)
				)
			projectCollection.update(queryCondition, updateParameter,true,true)
			
			}
			
			
			
			
			
			//member.save (flush:true)
			//print member.errors
		}
		catch(Exception e){
			LOG.error("auth user submit get exception."+e.getMessage())
			render "failure"
		}
		render "success"
		
	}
	
	
	/**
	 * 个人信息认证提交
	 * @param null
	 * @return null
	 *
	 * **/
	def userAuthSubmit(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		try{
			Member member = (Member)user
			String realName = params.realName
			String idNumber = params.idNumber
			String mobile = params.mobile
			String bankCard = params.bankCard
			String bankName = params.bankName
			String identifyimg = params.identifyimg
			String subBranch = params.subBranch
			String identifyimgre = params.identifyimgre
			String school = params.school
			String description = params.description
			//提交认证信息
			member.realName = realName
			member.idNumber = idNumber
			member.mobile = mobile
			member.bankCard = bankCard
			member.school = school
			member.description = description
			member.bankName = bankName
			member.subBranch = subBranch
			member.activeIDNumberPhoto = identifyimg
			member.negativeIDNumberPhoto = identifyimgre
			//置认证状态位等待审批
			member.verify = SCFIREConstants.USER_APPROVE_WAIT
			
			ResultEntry entry
			def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
			DBCollection projectCollection = db.getCollection("member")
			DBObject queryCondition= new BasicDBObject()
			queryCondition.put("_id",member.id)			
			try{
				entry = CreditService.queryCreditInfo(member.realName, member.idNumber, member.mobile, member.bankCard)
				def credits = CreditRank.findByIdNo(member.idNumber)
				if(credits == null){
					CreditRank credit = new CreditRank(entry)
					credit.member = member
					credit.save(flush:true)
					member.creditRank = credit
				}else{
					credits.transform(entry)
					member.creditRank = credits
				}
				
			}
			catch(Exception e){
				LOG.error("query user creditInfo get exception."+e.getMessage())
			}
			//更新用户信息
			//member.save flush:true
			BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject()
				.append("realName", member?.realName)
				.append("idNumber", member.idNumber)
				.append("mobile", member.mobile)
				.append("bankCard", member?.bankCard)
				.append("school", member?.school)
				.append("description", member?.description)
				.append("bankName", member?.bankName)
				.append("subBranch", member?.subBranch)
				.append("activeIDNumberPhoto", member?.activeIDNumberPhoto)
				.append("negativeIDNumberPhoto", member?.negativeIDNumberPhoto)
				.append("verify", member?.verify)
				.append("creditRank", member?.creditRank?.id)
				)
			projectCollection.update(queryCondition, updateParameter,true,true)
			
			//保存系统通知消息
			SystemMessage systemMessage = new SystemMessage()
			systemMessage.message = SCFIREConstants.SYSTEM_MESSAGE_USER_AUTH_SUBMIT
			systemMessage.date = new Date()
			systemMessage.member = member.id
			systemMessage.save flush:true
			
			render "success"
		}catch(Exception e){
			LOG.error("auth user submit get exception."+e.getMessage())
			render "failure"
		}		
		
	}
	
	
    /***********************START USER后台管理***************************************************/
	/**
	 * 个人信息
	 * @param null
	 * @return null
	 *
	 * **/
	def index(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
				
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "index", model: [user:user,roles:roles]
				}
				if("mobile".equals(str)){
					render view: "indexmb", model: [user:user,roles:roles]
				}
			}
			json {
				
			}
		}
		
	}
	/**
	 * 用户个人信息
	 * @param memberInstance
	 * @return null
	 *
	 * **/
	def show(Member memberInstance) {
		def userAgent = request.getHeader("User-Agent")
		String str = deviceInfoService.getDeviceInfo(userAgent)
	
		if(memberInstance == null){
			notFound()
			return
		}
		
		respond memberInstance
	}
	
	/**
	 * 查看个人信息
	 * @param memberInstance
	 * @return null
	 *
	 * **/
	def showInfo(Member memberInstance) {

		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		
		
		String memberid = params.userid;
		if(memberid == null){
			notFound()
			return
		}
		
		def member = Member.findById(memberid);
		
		withFormat {
			html {
				if("pc".equals(str)){
					render view: "userauthmb", model: [user:member]
				}
				if("mobile".equals(str)){
					render view: "userauthmb", model: [user:member]
				}
			}
			json {
				
			}
		}
	}
	
	/**
	 * 保存用户信息
	 * @param memberInstance
	 * @return null
	 *
	 * **/
	@Transactional
	def save(Member memberInstance) {
		def userAgent = request.getHeader("User-Agent")
		def gson = new Gson()
		String device = deviceInfoService.getDeviceInfo(userAgent)
				
		if (memberInstance == null) {
			notFound()
			return
		}
		
		if (memberInstance.hasErrors()) {
			withFormat {
				html {
					response.setContentType("text/html;charset=UTF-8")
					respond memberInstance.errors, view:'create'
				}
				json {
					gson.setResult(false)
					gson.setCode(403)
					gson.setInfo(["errortext":memberInstance.errors])
					render gson as JSON
				}
			}
			return
		}
		
		try{
			
			//保存用户信息
			memberInstance.save(flush:true)
			
			request.withFormat {
				form multipartForm {
					flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), memberInstance.id])
					redirect memberInstance
				}
				'*' { respond memberInstance, [status: CREATED] }
			}
			
			
			
		}catch(Exception e){
			gson.setResult(false)
			gson.setCode(500)
			gson.setInfo(["text":e.toString()])
			LOG.error("save user error. "+e.getMessage())
			render gson as JSON
		}
		
		
	}
	
	/**
	 * 编辑用户信息
	 * @param shopInstance
	 * @return null
	 *
	 * **/
	def edit(Member memberInstance) {
		respond memberInstance
	}
	
	/**
	 * 更新用户信息
	 * @param user id
	 * @return null
	 *
	 * **/
	@Transactional
	def update(Member memberInstance) {
		def gson = new Gson()
		
		if (memberInstance == null) {
			notFound()
			return
		}

		if (memberInstance.hasErrors()) {
			respond memberInstance.errors, view:'edit'
			return
		}

		memberInstance.save flush:true

		request.withFormat {
			form multipartForm {
				flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), memberInstance.id])
				redirect memberInstance
			}
			'*'{ respond memberInstance, [status: OK] }
		}
	}
	
	/**
	 * 删除用户信息
	 * @param null
	 * @return null
	 *
	 * **/
	def delete(Member memberInstance) {
		def gson = new Gson()
		
		if (memberInstance == null) {
			notFound()
			return
		}
		
		try{
			
			memberInstance.delete flush:true
			
		}catch(Exception e){
			gson.setResult(false)
			gson.setCode(500)
			gson.setInfo(["text":e.toString()])
			LOG.error("delete user error. "+e.getMessage())
			render gson as JSON
		}
	}
	
	
	/**
	 * 查询用户身份证注册状态
	 * @param null
	 * @return null
	 *
	 * **/
	def idExist() {
		def gson = new Gson()
		try{
			if(params.idNum){
				def member = Member.findByIdNumber(params.idNum)
				if(member != null){
					gson.setResult(false)
					gson.setCode(201)
					gson.setInfo(["text":"号码已存在"])
				}else{
					gson.setResult(true)
					gson.setCode(200)
					gson.setInfo(["text":"OK"])
				}
				render gson as JSON
				return
			}
			else{
				gson.setCode(403)
				gson.setInfo(["text":"UNKOWN ERROR"])
				render gson as JSON
				return
			}
		}catch(Exception e){
			gson.setResult(false)
			gson.setCode(500)
			gson.setInfo(["text":e.toString()])
			LOG.error("delete user error. "+e.getMessage())
			render gson as JSON
		}
	}
	
	/**
	 * 查询验证码
	 * @param null
	 * @return null
	 *
	 * **/
	def authCode() {
		def gson = new Gson()
		try{
			if(params.code && params.mobile){
				render CCPSMSService.CodeCheck(params.mobile ,params.code) as JSON
				return
			}
			else{
				gson.setCode(403)
				gson.setInfo(["text":"UNKOWN"])
				render gson as JSON
				return
			}
		}catch(Exception e){
			gson.setResult(false)
			gson.setCode(500)
			gson.setInfo(["text":e.toString()])
			LOG.error("delete user error. "+e.getMessage())
			render gson as JSON
		}
	}
	
	/**
	 * 查询用户手机注册状态
	 * @param null
	 * @return null
	 *
	 * **/
	def mobileExist() {
		def gson = new Gson()
		try{
			if(params.mobile){
				def member = Member.findByMobile(params.mobile)
				if(member != null){
					gson.setResult(false)
					gson.setCode(201)
					gson.setInfo(["text":"号码已存在"])
				}else{
					gson.setResult(true)
					gson.setCode(200)
					gson.setInfo(["text":"OK"])
				}
				render gson as JSON
				return
			}
			else{
				gson.setCode(403)
				gson.setInfo(["text":"UNKOWN"])
				render gson as JSON
				return
			}
		}catch(Exception e){
			gson.setResult(false)
			gson.setCode(500)
			gson.setInfo(["text":e.toString()])
			LOG.error("delete user error. "+e.getMessage())
			render gson as JSON
		}

	}
	
	/***********************END USER后台管理***************************************************/
	/**
	 * 用户信息未找到
	 * @param null
	 * @return null
	 *
	 * **/
	protected void notFound() {
		def gson = new Gson()
		withFormat {
			html {
				flash.message = "未找到该用户！"
				redirect (controller: "errors", action: "notFound")
			}
			json {
				gson.setResult(false)
				gson.setCode(404)
				gson.setInfo(["text": "未找到该用户！"])
				render gson as JSON
			}
		}
	}
	
	/**
	 * 个人信息认证PC端第三方短信认证页面
	 * @param null
	 * @return null
	 *
	 * **/
	def userAuthPc(){
		def format = request.getHeader("format")
		def userAgent = request.getHeader("User-Agent")
		def str = deviceInfoService.getDeviceInfo(userAgent)
		//获取用户基本信息
		def user = springSecurityService.getCurrentUser()
		def roles = springSecurityService.getAuthentication()?.authorities
		
		withFormat {
			html { 
				if("pc".equals(str)){
					render view: "userauthpc", model: [user:user,roles:roles]
				}
				if("mobile".equals(str)){
					render view: "userauthpc", model: [user:user,roles:roles]
				}
			}
		}
	}
}
